package com.csot.ry.controller;

import cn.hutool.core.util.StrUtil;
import com.csot.ry.domain.TCoarseSegment;
import com.csot.ry.service.ITCoarseSegmentService;
import com.csot.ry.util.CacheKitUtil;
import com.csot.common.annotation.Log;
import com.csot.common.core.controller.BaseController;
import com.csot.common.core.domain.AjaxResult;
import com.csot.common.core.page.TableDataInfo;
import com.csot.common.enums.BusinessType;
import com.csot.common.utils.poi.ExcelUtil;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

/**
 * 粗粒度ip段Controller
 *
 * @author 刘沙
 * @date 2022-05-31
 */
@RestController
@RequestMapping("/ipmanagement/coarsesegment")
public class TCoarseSegmentController extends BaseController {
    @Autowired
    private ITCoarseSegmentService tCoarseSegmentService;

    /**
     * 查询粗粒度ip段列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarsesegment:list')")
    @GetMapping("/list/{type}")
    public TableDataInfo list(TCoarseSegment tCoarseSegment, @PathVariable("type") String type) {
//        String parentId = getLoginUser().getUser().getDept().getParentId() + "";
//        if (StrUtil.isBlankIfStr(tCoarseSegment.getIpCity()) && CacheKitUtil.ip_dept != null && StrUtil.isNotEmpty(parentId) && !"0".equals(parentId)) {
//            tCoarseSegment.setIpCity(CacheKitUtil.ip_dept.get(parentId + ""));
//        }
        String parentId = getLoginUser().getUser().getDept().getParentId() + "";
        if (CacheKitUtil.ip_dept != null && StrUtil.isNotEmpty(parentId) && !"0".equals(parentId)) {
            tCoarseSegment.setIpCity(CacheKitUtil.ip_dept.get(parentId + ""));
        }
        startPage();
        tCoarseSegment.setIpType(type.toLowerCase());
        List<TCoarseSegment> list = tCoarseSegmentService.selectTCoarseSegmentList(tCoarseSegment);
        return getDataTable(list);
    }

    /**
     * 导出粗粒度ip段列表
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarsesegment:export')")
    @Log(title = "粗粒度ip段", businessType = BusinessType.EXPORT)
    @PostMapping("/export/{type}")
    public void export(HttpServletResponse response, TCoarseSegment tCoarseSegment, @PathVariable("type") String type) {
        String parentId = getLoginUser().getUser().getDept().getParentId() + "";
        if (CacheKitUtil.ip_dept != null && StrUtil.isNotEmpty(parentId) && !"0".equals(parentId)) {
            tCoarseSegment.setIpCity(CacheKitUtil.ip_dept.get(parentId + ""));
        }
        tCoarseSegment.setIpType(type.toLowerCase());
        List<TCoarseSegment> list = tCoarseSegmentService.selectTCoarseSegmentList(tCoarseSegment);
        for (TCoarseSegment t : list) {
            t.setIpType(CacheKitUtil.ip_type.get(t.getIpType()));
            t.setIpCity(CacheKitUtil.ip_city.get(t.getIpCity()));
            t.setRecordStatus(CacheKitUtil.ip_record.get(t.getRecordStatus()));
            t.setIpStatus(CacheKitUtil.ip_status.get(t.getIpStatus()));
            t.setIpUseType(CacheKitUtil.ip_use_type.get(t.getIpUseType()));
        }
        ExcelUtil<TCoarseSegment> util = new ExcelUtil<TCoarseSegment>(TCoarseSegment.class);
        util.exportExcel(response, list, "粗粒度ip段数据");
    }

    /**
     * 获取粗粒度ip段详细信息
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarsesegment:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(tCoarseSegmentService.selectTCoarseSegmentById(id));
    }

    /**
     * 新增粗粒度ip段
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarsesegment:add')")
    @Log(title = "粗粒度ip段", businessType = BusinessType.INSERT)
    @PostMapping(value = "/{type}")
    public AjaxResult add(@RequestBody TCoarseSegment tCoarseSegment, @PathVariable("type") String type) {
        tCoarseSegment.setIpType(type.toLowerCase());
        return toAjax(tCoarseSegmentService.insertTCoarseSegment(tCoarseSegment));
    }

    /**
     * 修改粗粒度ip段
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarsesegment:edit')")
    @Log(title = "粗粒度ip段", businessType = BusinessType.UPDATE)
    @PutMapping(value = "/{type}")
    public AjaxResult edit(@RequestBody TCoarseSegment tCoarseSegment, @PathVariable("type") String type) {
        tCoarseSegment.setIpType(type.toLowerCase());
        return toAjax(tCoarseSegmentService.updateTCoarseSegment(tCoarseSegment));
    }

    /**
     * 删除粗粒度ip段
     */
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarsesegment:remove')")
    @Log(title = "粗粒度ip段", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tCoarseSegmentService.deleteTCoarseSegmentByIds(ids));
    }

    @Log(title = "粗粒度ip段导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('ipmanagement:coarsesegment:import')")
    @PostMapping("/importData/{type}")
    public AjaxResult importData(MultipartFile file, boolean updateSupport, @PathVariable("type") String type) throws Exception {
        try {
            ExcelUtil<TCoarseSegment> util = new ExcelUtil<TCoarseSegment>(TCoarseSegment.class);
            List<TCoarseSegment> tCoarseSegmentList = util.importExcel(file.getInputStream());
            tCoarseSegmentList.stream().forEach(t -> {
                t.setIpType(type.toLowerCase());
            });
            String message = tCoarseSegmentService.importCoarseSegment(tCoarseSegmentList, updateSupport);
            return AjaxResult.success(message);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        try {
            String path = System.getProperty("user.dir");
            path = path + File.separator + "Template" + File.separator + "coarsesegment.xlsx";
            IOUtils.write(Files.readAllBytes(Paths.get(path)),
                    response.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            logger.error("下载ip段模块异常", e);
        }
    }
}
